from collections import Iterable,Iterator

import pymongo
from pymongo.results import InsertOneResult,InsertManyResult,DeleteResult,UpdateResult
if __name__ == '__main__':
    mongo = pymongo.MongoClient("mongodb://127.0.0.1:27017/")
    # 切换数据库
    my_db = mongo["my_db"]
    # 切换集合
    my_collection = my_db["my_collection"]

    # 没有条件(过滤)的查询
    # ret = my_collection.find_one()
    # ret = my_collection.find_one({})
    # ret = my_collection.find_one({},{"_id":0}) # 字段映射
    # print(ret)

    # 查看所有文档
    # ret = my_collection.find()
    # print(ret)
    # for document in ret:
    #     print(document) # 字典格式
    #     print(document["name"]) # 获取文档中的键key/域field/字段

    # 返回结果进行字段映射
    # for document in my_collection.find({}, {"_id": 0, "name": 1, "mobile": 1}):
    #     print(document)

    # 按条件查询数据
    # query = {"age": 20}
    # document_list = my_collection.find(query,{"_id":0})
    # for document in document_list:
    #     print(document)

    # 使用比较运算来查询数据
    # query = {"age": {"$gt": 17}} # age > 17
    # document_list = my_collection.find(query)
    # for document in document_list:
    #     print(document)

    # 查询结果进行排序 1为升序, -1为降序
    # for document in my_collection.find({}, {"_id": 0}).sort("age",-1):
    #     print(document)

    # 多个字段进行第一排序,第二排序的情况
    # for document in my_collection.find().sort([("age",-1),("_id",1)]):
    #     print(document)

    # limit和skip使用
    # document_list = my_collection.find().limit(2).skip(2)
    # for document in document_list:
    #     print(document)

    # 自定义条件函数
    # document_list = my_collection.find({"$where": "this.age==20"}) # 是js代码,this在javascript表示当前而且当前文档对象
    # for document in document_list:
    #     print(document)

    # document_list = my_collection.find({"$where": "this.age<27 && this.age > 1"})
    my_db = mongo["test"]
    # 切换集合
    my_collection = my_db["orders"]

    document_list = my_collection.find({"$where": """
        for( goods of this.items){
            if(goods.goods_attr > 1700 && goods.goods_attr < 1800){
                return true;
            }else{
                return false;
            }
        }
    """})
    for document in document_list:
        print(document)
